from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QListWidget, QPushButton, QVBoxLayout, QHBoxLayout, QApplication, QLabel, \
    QLineEdit, QDialogButtonBox, QMessageBox, QListWidgetItem


class StringListDlg(QDialog):
    def __init__(self, catList, parent=None, category="Fruit"):
        super(StringListDlg, self).__init__(parent)

        self.listWidget = QListWidget()
        self.catList = catList
        if len(self.catList) == 0:
            self.catList = ['One', 'Two']
        self.listWidget.addItems(catList)

        addBtn = QPushButton("&Add...")
        editBtn = QPushButton("&Edit...")
        removeBtn = QPushButton("&Remove...")
        upBtn = QPushButton("&Up")
        downBtn = QPushButton("&Down")
        sortBtn = QPushButton("&Sort")
        closeBtn = QPushButton("Close")

        btnLayout = QVBoxLayout()
        btnLayout.addWidget(addBtn)
        btnLayout.addWidget(editBtn)
        btnLayout.addWidget(removeBtn)
        btnLayout.addWidget(upBtn)
        btnLayout.addWidget(downBtn)
        btnLayout.addWidget(sortBtn)
        btnLayout.addWidget(closeBtn)

        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(btnLayout)
        self.setLayout(layout)

        self.setWindowTitle("ListWidget")

        addBtn.clicked.connect(self.add)
        editBtn.clicked.connect(self.edit)
        removeBtn.clicked.connect(self.remove)
        upBtn.clicked.connect(self.up)
        downBtn.clicked.connect(self.down)
        sortBtn.clicked.connect(self.sort)
        closeBtn.clicked.connect(self.close)

    def add(self):
        addDlg = AddDlg()
        addDlg.lineText.setText("Type a New Item")
        addDlg.lineText.selectAll()
        addDlg.lineText.setFocus()
        if addDlg.exec():
            newItem = QListWidgetItem(addDlg.lineText.text())
            if newItem not in ("Type a New Item", ""):
                self.listWidget.addItem(newItem)

    def edit(self):
        """
        开始用的编辑后台列表catelist的方法，虽然仍然可编辑，但是在更新的时候，listWidget的项排序有变化，显得不友好。
        现在看，直接更新项的文本更合理。
        :return:
        """
        item = self.listWidget.currentItem()  # 取得项目
        text = item.text()  # 取得项的文本
        editDlg = AddDlg()
        editDlg.lineText.setText(text)  # 文本带进编辑框
        if editDlg.exec():
            if editDlg.lineText.text():  # 这里应有更多的验证
                item.setText(editDlg.lineText.text())  # 将新文本赋予项目

    def remove(self):
        """很奇怪removeItemWidget不起作用"""
        reply = QMessageBox.warning(self, "Take Item", "Are you sure to take the Item? it'll lost forever!",
                                    QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel)
        if reply:
            index = self.listWidget.currentRow()
            self.listWidget.takeItem(index)

    def up(self):
        index = self.listWidget.currentRow()
        item = self.listWidget.currentItem()  # 选中项
        upItem = self.listWidget.takeItem(index - 1)  # 取走上面的项
        self.listWidget.insertItem(index, upItem)  # 在原位置插入上面的项
        self.listWidget.insertItem(index - 1, item)  # 在上一个位置插入先中的项

    def down(self):
        index = self.listWidget.currentRow()
        item = self.listWidget.currentItem()  # 选中项
        downItem = self.listWidget.takeItem(index + 1)  # 取走上面的项
        self.listWidget.insertItem(index, downItem)  # 在原位置插入上面的项
        self.listWidget.insertItem(index + 1, item)  # 在上一个位置插入先中的项

    def sort(self):
        self.listWidget.sortItems(Qt.AscendingOrder)  # 借鉴http://blog.csdn.net/fengyu09/article/details/39639413


class AddDlg(QDialog):
    def __init__(self, parent=None):
        super(AddDlg, self).__init__(parent)

        addLabel = QLabel("Add Fruit")
        self.lineText = QLineEdit()
        btnBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        layout = QVBoxLayout()
        layout.addWidget(addLabel)
        layout.addWidget(self.lineText)
        layout.addWidget(btnBox)
        self.setLayout(layout)

        btnBox.accepted.connect(self.accept)
        btnBox.rejected.connect(self.reject)

    def accept(self):
        item = self.lineText.text()
        if not len(item) > 0:
            QMessageBox.warning(self, "Warning", "Item can not be None")
        else:

            # print(self.catlist)
            QDialog.accept(self)


if __name__ == '__main__':
    import sys

    fruit = ["Banana", "Apple", "Elderberry", "Clementine", "Fig", "Guava", "Mango", "Honeydew Melon",
             "Date", "Watermelon", "Tangerine", "Ugli Fruit", "Juniperberry", "Kiwi",
             "Lemon", "Nectarine", "Plum", "Raspberry", "Strawberry", "Orange"]
    app = QApplication(sys.argv)
    form = StringListDlg(category="Fruit", catList=fruit)
    # form=AddDlg(catlist=fruit)
    form.show()
    sys.exit(app.exec())
